<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>听力管理系统 - 后台管理</title>
    <!-- Element UI CSS -->
    <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui@2.15.14/lib/theme-chalk/index.css"> -->
    <link rel="stylesheet" href="lib/element-ui.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    <div id="admin-app">
        <!-- 顶部导航 -->
        <el-header class="admin-header">
            <div class="header-content">
                <h2>{{ siteTitle }}</h2>
                <div class="header-actions">
                    <el-button @click="showUpdateTitleDialog">修改标题</el-button>
                    <el-button @click="showChangePasswordDialog">修改密码</el-button>
                    <el-button type="danger" @click="handleLogout">退出登录</el-button>
                </div>
            </div>
        </el-header>

        <!-- 主要内容 -->
        <el-main class="admin-main">
            <el-tabs v-model="activeTab" type="card">
                <!-- 一级分类管理 -->
                <el-tab-pane label="一级分类管理" name="level1">
                    <div class="toolbar">
                        <el-button type="primary" @click="showAddLevel1Dialog">添加一级分类</el-button>
                    </div>
                    <el-table :data="level1List" border>
                        <el-table-column prop="categoryId" label="ID" width="80"></el-table-column>
                        <el-table-column prop="name" label="分类名称"></el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="showEditLevel1Dialog(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="handleDeleteLevel1(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 二级分类管理 -->
                <el-tab-pane label="二级分类管理" name="level2">
                    <div class="toolbar">
                        <el-button type="primary" @click="showAddLevel2Dialog">添加二级分类</el-button>
                    </div>
                    <el-table :data="level2List" border>
                        <el-table-column prop="subcategoryId" label="ID" width="80"></el-table-column>
                        <el-table-column prop="subcategoryName" label="二级分类名称"></el-table-column>
                        <el-table-column prop="categoryName" label="所属一级分类"></el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="showEditLevel2Dialog(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="handleDeleteLevel2(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 听力文件管理 -->
                <el-tab-pane label="听力文件管理" name="audio">
                    <div class="toolbar">
                        <el-button type="primary" @click="showUploadDialog">上传文件</el-button>
                    </div>
                    <!-- 听力文件管理表格 -->
                    <el-table :data="audioList" border>
                        <el-table-column prop="audioId" label="ID" width="80"></el-table-column>
                        <el-table-column prop="title" label="文件标题"></el-table-column>
                        <el-table-column prop="description" label="描述"></el-table-column>
                        <el-table-column prop="categoryName" label="一级分类"></el-table-column>
                        <el-table-column prop="subcategoryName" label="二级分类"></el-table-column>
                        <el-table-column prop="isVisible" label="是否可见" width="100">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.isVisible ? 'success' : 'danger'">
                                    {{ scope.row.isVisible ? '是' : '否' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="showEditAudioDialog(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger"
                                    @click="handleDeleteAudio(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-main>

        <!-- 修改标题对话框 -->
        <el-dialog title="修改网站标题" :visible.sync="updateTitleDialogVisible" :close-on-click-modal="false" width="400px">
            <el-form :model="titleForm">
                <el-form-item label="新标题">
                    <el-input v-model="titleForm.title"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="updateTitleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateTitle">确定</el-button>
            </div>
        </el-dialog>

        <!-- 修改密码对话框 -->
        <el-dialog title="修改密码" :visible.sync="changePasswordDialogVisible" :close-on-click-modal="false" width="400px">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input type="password" v-model="passwordForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input type="password" v-model="passwordForm.newPassword"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="changePasswordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleChangePassword">确定</el-button>
            </div>
        </el-dialog>

        <!-- 添加/编辑一级分类对话框 -->
        <el-dialog :title="level1DialogTitle" :visible.sync="level1DialogVisible" :close-on-click-modal="false"
            width="400px">
            <el-form :model="level1Form" :rules="level1Rules" ref="level1Form">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="level1Form.name" placeholder="请输入分类名称"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="level1DialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSaveLevel1">确定</el-button>
            </div>
        </el-dialog>

        <!-- 添加/编辑二级分类对话框 -->
        <el-dialog :title="level2DialogTitle" :visible.sync="level2DialogVisible" :close-on-click-modal="false"
            width="400px">
            <el-form :model="level2Form" :rules="level2Rules" ref="level2Form">
                <el-form-item label="一级分类" prop="categoryId">
                    <el-select v-model="level2Form.categoryId" placeholder="请选择一级分类" style="width: 100%">
                        <el-option v-for="item in level1List" :key="item.categoryId" :label="item.name"
                            :value="item.categoryId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类名称" prop="subcategoryName">
                    <el-input v-model="level2Form.subcategoryName" placeholder="请输入二级分类名称"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="level2DialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSaveLevel2">确定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑听力文件对话框 -->
        <el-dialog title="编辑听力文件" :visible.sync="editAudioDialogVisible" :close-on-click-modal="false" width="500px">
            <el-form :model="editAudioForm" :rules="audioRules" ref="editAudioForm">
                <el-form-item label="一级分类" prop="selectedCategoryId">
                    <el-select v-model="editAudioForm.selectedCategoryId" placeholder="请选择一级分类"
                        @change="onEditCategoryChange" class="modern-select" size="medium">
                        <el-option v-for="item in level1List" :key="item.categoryId" :label="item.name"
                            :value="item.categoryId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="二级分类" prop="categoryId">
                    <el-select v-model="editAudioForm.categoryId" placeholder="请先选择一级分类" class="modern-select"
                        size="medium" :disabled="!editAudioForm.selectedCategoryId">
                        <el-option v-for="item in editLevel2List" :key="item.subcategoryId"
                            :label="item.subcategoryName" :value="item.subcategoryId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件标题" prop="title">
                    <el-input v-model="editAudioForm.title" placeholder="请输入文件标题"></el-input>
                </el-form-item>
                <el-form-item label="文件描述">
                    <el-input type="textarea" v-model="editAudioForm.description" placeholder="请输入文件描述"></el-input>
                </el-form-item>
                <el-form-item label="是否可见">
                    <el-switch v-model="editAudioForm.isVisible"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="editAudioDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSaveAudio">确定</el-button>
            </div>
        </el-dialog>

        <!-- 上传文件对话框 -->
        <el-dialog :visible.sync="uploadDialogVisible" width="520px" :close-on-click-modal="false"
            class="modern-upload-dialog">
            <div class="dialog-header">
                <i class="el-icon-upload2 header-icon"></i>
                <span>上传新的听力文件</span>
            </div>

            <el-form :model="uploadForm" :rules="audioRules" ref="uploadForm" label-width="100px" class="modern-form">
                <el-form-item label="一级分类" prop="categoryId">
                    <el-select v-model="uploadForm.categoryId" placeholder="请选择一级分类" @change="onUploadCategoryChange"
                        class="modern-select" size="medium">
                        <el-option v-for="item in level1List" :key="item.categoryId" :label="item.name"
                            :value="item.categoryId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="二级分类" prop="subcategoryId">
                    <el-select v-model="uploadForm.subcategoryId" placeholder="请选择二级分类" class="modern-select"
                        size="medium">
                        <el-option v-for="item in uploadLevel2List" :key="item.subcategoryId"
                            :label="item.subcategoryName" :value="item.subcategoryId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文件标题" prop="title">
                    <el-input v-model="uploadForm.title" placeholder="请输入文件标题" class="modern-input" size="medium">
                    </el-input>
                </el-form-item>

                <el-form-item label="文件描述">
                    <el-input type="textarea" v-model="uploadForm.description" placeholder="请输入文件描述" :rows="3"
                        class="modern-textarea" resize="none">
                    </el-input>
                </el-form-item>

                <el-form-item label="是否可见">
                    <el-switch v-model="uploadForm.isVisible" active-text="可见" inactive-text="隐藏" class="modern-switch">
                    </el-switch>
                </el-form-item>

                <el-form-item label="选择文件" prop="file" class="file-upload-item">
                    <div class="upload-area" @click="$refs.upload.$el.querySelector('input').click()">
                        <div class="upload-content" v-if="!selectedFileName">
                            <i class="el-icon-upload upload-icon"></i>
                            <div class="upload-text">点击或拖拽文件到此处</div>
                            <div class="upload-hint">支持 mp3, wav 等音频格式</div>
                        </div>
                        <div class="file-selected" v-else>
                            <i class="el-icon-document file-icon"></i>
                            <div class="file-info">
                                <div class="file-name">{{ selectedFileName }}</div>
                                <div class="file-size" v-if="uploadForm.file">{{ formatFileSize(uploadForm.file.size) }}
                                </div>
                            </div>
                            <el-button type="text" class="change-file-btn"
                                @click.stop="$refs.upload.$el.querySelector('input').click()">
                                重新选择
                            </el-button>
                        </div>
                    </div>
                    <el-upload ref="upload" :auto-upload="false" :action="''" :on-change="handleFileChange"
                        :show-file-list="false" :before-upload="beforeUpload" style="display: none;">
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="uploadDialogVisible = false" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleUpload" :loading="uploadLoading" class="upload-btn"
                    :disabled="!uploadForm.file">
                    {{ uploadLoading ? '上传中...' : '开始上传' }}
                </el-button>
            </div>
        </el-dialog>
    </div>

    <!-- Vue.js -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> -->
    <!-- Element UI JS -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.14/lib/index.js"></script> -->
    <!-- Axios -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script> -->

    <script src="lib/vue.js"></script>
    <script src="lib/element-ui.js"></script>
    <script src="lib/axios.js"></script>

    <!-- 自定义JS -->
    <script src="js/auth.js"></script>
    <script src="js/api.js"></script>

    <script>
        // 检查登录状态
        if (!Auth.requireAuth()) {
            // 如果未登录，auth.js会自动跳转到登录页
        }

        new Vue({
            el: '#admin-app',
            data() {
                return {
                    siteTitle: '听力管理系统',
                    activeTab: 'level1',

                    // 数据列表
                    level1List: [],
                    level2List: [],
                    audioList: [],
                    uploadLevel2List: [], // 上传时用的二级分类列表
                    editLevel2List: [],   // 编辑时用的二级分类列表

                    // 对话框状态
                    updateTitleDialogVisible: false,
                    changePasswordDialogVisible: false,
                    level1DialogVisible: false,
                    level2DialogVisible: false,
                    editAudioDialogVisible: false,
                    uploadDialogVisible: false,

                    // 表单数据
                    titleForm: { title: '' },
                    passwordForm: { oldPassword: '', newPassword: '' },
                    level1Form: { categoryId: null, name: '' },
                    level2Form: { subcategoryId: null, categoryId: null, subcategoryName: '' },
                    editAudioForm: {
                        audioId: null,
                        title: '',
                        description: '',
                        selectedCategoryId: null,  // 新字段：用于选择一级分类
                        categoryId: null,          // 这个就是传给后端的二级分类ID
                        isVisible: true
                    },
                    uploadForm: {
                        title: '',
                        description: '',
                        categoryId: null,
                        subcategoryId: null,
                        isVisible: true,
                        file: null
                    },
                    selectedFileName: '',
                    uploadLoading: false,

                    // 表单规则
                    passwordRules: {
                        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
                        newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }]
                    },
                    level1Rules: {
                        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
                    },
                    level2Rules: {
                        categoryId: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
                        subcategoryName: [{ required: true, message: '请输入二级分类名称', trigger: 'blur' }]
                    },
                    audioRules: {
                        categoryId: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
                        subcategoryId: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
                        title: [{ required: true, message: '请输入文件标题', trigger: 'blur' }],
                        file: [{ required: true, message: '请选择文件', trigger: 'change' }]
                    },

                    // 编辑状态
                    isEditingLevel1: false,
                    isEditingLevel2: false,
                    isEditingAudio: false
                };
            },
            computed: {
                level1DialogTitle() {
                    return this.isEditingLevel1 ? '编辑一级分类' : '添加一级分类';
                },
                level2DialogTitle() {
                    return this.isEditingLevel2 ? '编辑二级分类' : '添加二级分类';
                }
            },
            async mounted() {
                await this.loadSiteTitle();
                await this.loadAllData();
            },
            methods: {
                // 文件大小格式化
                formatFileSize(bytes) {
                    if (bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                },

                // 上传前检查
                beforeUpload(file) {
                    const isAudio = file.type.startsWith('audio/');
                    const isLt100M = file.size / 1024 / 1024 < 100;

                    if (!isAudio) {
                        this.$message.error('只能上传音频文件!');
                        return false;
                    }
                    if (!isLt100M) {
                        this.$message.error('音频文件大小不能超过 100MB!');
                        return false;
                    }
                    return true;
                },
                async loadSiteTitle() {
                    try {
                        const result = await sysApi.getTitle();
                        if (result && result.data) {
                            this.siteTitle = result.data;
                        }
                    } catch (error) {
                        console.error('加载标题失败:', error);
                    }
                },

                async loadAllData() {
                    await Promise.all([
                        this.loadLevel1List(),
                        this.loadLevel2List(),
                        this.loadAudioList()
                    ]);
                },

                async loadLevel1List() {
                    try {
                        const result = await categoryApi.level1.list();
                        this.level1List = result.data || [];
                    } catch (error) {
                        this.$message.error('加载一级分类失败: ' + error.message);
                    }
                },

                async loadLevel2List() {
                    try {
                        const result = await categoryApi.level2.list();
                        this.level2List = result.data || [];
                    } catch (error) {
                        this.$message.error('加载二级分类失败: ' + error.message);
                    }
                },

                async loadAudioList() {
                    try {
                        const result = await audioApi.list();
                        this.audioList = result.data || [];
                    } catch (error) {
                        this.$message.error('加载听力文件失败: ' + error.message);
                    }
                },

                async onUploadCategoryChange(categoryId) {
                    if (categoryId) {
                        try {
                            const result = await categoryApi.level2.listByCategory(categoryId); // 直接传递categoryId
                            this.uploadLevel2List = result.data || [];
                            this.uploadForm.subcategoryId = null; // 重置二级分类选择
                        } catch (error) {
                            this.$message.error('加载二级分类失败: ' + error.message);
                            this.uploadLevel2List = [];
                        }
                    } else {
                        this.uploadLevel2List = [];
                        this.uploadForm.subcategoryId = null;
                    }
                },

                async onEditCategoryChange(categoryId) {
                    if (categoryId) {
                        try {
                            const result = await categoryApi.level2.listByCategory(categoryId); // 直接传递categoryId
                            this.editLevel2List = result.data || [];
                            this.editAudioForm.subcategoryId = null; // 重置二级分类选择
                        } catch (error) {
                            this.$message.error('加载二级分类失败: ' + error.message);
                            this.editLevel2List = [];
                        }
                    } else {
                        this.editLevel2List = [];
                        this.editAudioForm.subcategoryId = null;
                    }
                },

                // 各种对话框显示方法
                showUpdateTitleDialog() {
                    this.titleForm.title = this.siteTitle;
                    this.updateTitleDialogVisible = true;
                },

                showChangePasswordDialog() {
                    this.passwordForm = { oldPassword: '', newPassword: '' };
                    this.changePasswordDialogVisible = true;
                },

                showAddLevel1Dialog() {
                    this.isEditingLevel1 = false;
                    this.level1Form = { categoryId: null, name: '' };
                    this.level1DialogVisible = true;
                    this.$nextTick(() => {
                        this.$refs.level1Form && this.$refs.level1Form.clearValidate();
                    });
                },

                showEditLevel1Dialog(row) {
                    this.isEditingLevel1 = true;
                    this.level1Form = { ...row };
                    this.level1DialogVisible = true;
                },

                showAddLevel2Dialog() {
                    this.isEditingLevel2 = false;
                    this.level2Form = { subcategoryId: null, categoryId: null, subcategoryName: '' };
                    this.level2DialogVisible = true;
                    this.$nextTick(() => {
                        this.$refs.level2Form && this.$refs.level2Form.clearValidate();
                    });
                },

                showEditLevel2Dialog(row) {
                    this.isEditingLevel2 = true;
                    this.level2Form = {
                        subcategoryId: row.subcategoryId,
                        categoryId: row.categoryId,
                        subcategoryName: row.subcategoryName
                    };
                    this.level2DialogVisible = true;
                },

                showEditAudioDialog(row) {
                    this.isEditingAudio = true;

                    // 先找到这个文件对应的二级分类属于哪个一级分类
                    const findParentCategory = () => {
                        if (row.subcategoryId && this.level2List.length > 0) {
                            const subcategory = this.level2List.find(item => item.subcategoryId === row.subcategoryId);
                            return subcategory ? subcategory.categoryId : null;
                        }
                        return null;
                    };

                    this.editAudioForm = {
                        audioId: row.audioId || row.id,
                        title: row.title,
                        description: row.description,
                        selectedCategoryId: findParentCategory(),  // 设置对应的一级分类ID
                        categoryId: row.subcategoryId,             // 二级分类ID，传给后端作为categoryId
                        isVisible: row.isVisible
                    };

                    // 如果找到了一级分类，加载对应的二级分类
                    if (this.editAudioForm.selectedCategoryId) {
                        this.onEditCategoryChange(this.editAudioForm.selectedCategoryId).then(() => {
                            this.editAudioDialogVisible = true;
                        });
                    } else {
                        this.editAudioDialogVisible = true;
                    }

                    this.$nextTick(() => {
                        this.$refs.editAudioForm && this.$refs.editAudioForm.clearValidate();
                    });
                },

                showUploadDialog() {
                    this.uploadForm = {
                        title: '',
                        description: '',
                        categoryId: null,
                        subcategoryId: null,
                        isVisible: true,
                        file: null
                    };
                    this.selectedFileName = '';
                    this.uploadLevel2List = [];
                    this.uploadDialogVisible = true;
                    this.$nextTick(() => {
                        this.$refs.uploadForm && this.$refs.uploadForm.clearValidate();
                    });
                },

                // 各种处理函数
                async handleUpdateTitle() {
                    try {
                        const result = await sysApi.updateTitle(this.titleForm.title);
                        if (result && result.code === 200) {
                            this.siteTitle = this.titleForm.title;
                            this.updateTitleDialogVisible = false;
                            this.$message.success('标题更新成功');
                        }
                    } catch (error) {
                        this.$message.error('更新标题失败: ' + error.message);
                    }
                },

                async handleChangePassword() {
                    this.$refs.passwordForm.validate(async (valid) => {
                        if (valid) {
                            try {
                                const result = await sysApi.updatePassword(
                                    this.passwordForm.oldPassword,
                                    this.passwordForm.newPassword
                                );
                                if (result && result.code === 200) {
                                    this.changePasswordDialogVisible = false;
                                    this.$message.success('密码修改成功');
                                }
                            } catch (error) {
                                this.$message.error('修改密码失败: ' + error.message);
                            }
                        }
                    });
                },

                async handleSaveLevel1() {
                    this.$refs.level1Form.validate(async (valid) => {
                        if (valid) {
                            try {
                                let result;
                                if (this.isEditingLevel1) {
                                    result = await categoryApi.level1.update(this.level1Form);
                                } else {
                                    result = await categoryApi.level1.add(this.level1Form);
                                }

                                if (result && result.code === 200) {
                                    this.level1DialogVisible = false;
                                    await this.loadLevel1List();
                                    this.$message.success('操作成功');
                                }
                            } catch (error) {
                                this.$message.error('操作失败: ' + error.message);
                            }
                        }
                    });
                },

                async handleSaveLevel2() {
                    this.$refs.level2Form.validate(async (valid) => {
                        if (valid) {
                            try {
                                let result;
                                if (this.isEditingLevel2) {
                                    result = await categoryApi.level2.update(this.level2Form);
                                } else {
                                    result = await categoryApi.level2.add(this.level2Form);
                                }

                                if (result && result.code === 200) {
                                    this.level2DialogVisible = false;
                                    await this.loadLevel2List();
                                    this.$message.success('操作成功');
                                }
                            } catch (error) {
                                this.$message.error('操作失败: ' + error.message);
                            }
                        }
                    });
                },

                async handleSaveAudio() {
                    this.$refs.editAudioForm.validate(async (valid) => {
                        if (valid) {
                            try {
                                const result = await audioApi.update(this.editAudioForm);
                                if (result && result.code === 200) {
                                    this.editAudioDialogVisible = false;
                                    await this.loadAudioList();
                                    this.$message.success('更新成功');
                                }
                            } catch (error) {
                                this.$message.error('更新失败: ' + error.message);
                            }
                        }
                    });
                },

                async handleDeleteLevel1(row) {
                    try {
                        await this.$confirm('确定要删除这个分类吗？', '提示', {
                            type: 'warning'
                        });

                        const result = await categoryApi.level1.delete(row.categoryId);
                        if (result && result.code === 200) {
                            await this.loadLevel1List();
                            this.$message.success('删除成功');
                        }
                    } catch (error) {
                        if (error !== 'cancel') {
                            this.$message.error('删除失败: ' + error.message);
                        }
                    }
                },

                async handleDeleteLevel2(row) {
                    try {
                        await this.$confirm('确定要删除这个分类吗？', '提示', {
                            type: 'warning'
                        });

                        const result = await categoryApi.level2.delete(row.subcategoryId);
                        if (result && result.code === 200) {
                            await this.loadLevel2List();
                            this.$message.success('删除成功');
                        }
                    } catch (error) {
                        if (error !== 'cancel') {
                            this.$message.error('删除失败: ' + error.message);
                        }
                    }
                },

                handleFileChange(file) {
                    this.uploadForm.file = file.raw;
                    this.selectedFileName = file.name;
                    // 触发文件字段验证
                    this.$refs.uploadForm && this.$refs.uploadForm.validateField('file');
                },

                async handleUpload() {
                    this.$refs.uploadForm.validate(async (valid) => {
                        if (valid) {
                            if (!this.uploadForm.file) {
                                this.$message.warning('请选择要上传的文件');
                                return;
                            }

                            this.uploadLoading = true;

                            const formData = new FormData();
                            formData.append('file', this.uploadForm.file);
                            formData.append('title', this.uploadForm.title);
                            formData.append('description', this.uploadForm.description || '');
                            formData.append('categoryId', this.uploadForm.subcategoryId);
                            formData.append('isVisible', this.uploadForm.isVisible);

                            try {
                                const result = await audioApi.upload(formData);
                                if (result && result.code === 200) {
                                    this.uploadDialogVisible = false;
                                    await this.loadAudioList();
                                    this.$message.success('文件上传成功');
                                }
                            } catch (error) {
                                this.$message.error('文件上传失败: ' + error.message);
                            } finally {
                                this.uploadLoading = false;
                            }
                        }
                    });
                },

                async handleDeleteAudio(row) {
                    try {
                        await this.$confirm('确定要删除这个文件吗？', '提示', {
                            type: 'warning'
                        });

                        // 使用 audioId，如果没有则使用 id
                        const audioId = row.audioId || row.id;
                        const result = await audioApi.delete(audioId);
                        if (result && result.code === 200) {
                            await this.loadAudioList();
                            this.$message.success('删除成功');
                        }
                    } catch (error) {
                        if (error !== 'cancel') {
                            this.$message.error('删除失败: ' + error.message);
                        }
                    }
                },

                async handleLogout() {
                    try {
                        await this.$confirm('确定要退出登录吗？', '提示', {
                            type: 'warning'
                        });

                        await sysApi.logout();
                        Auth.clearUser();
                        window.location.href = 'login.html';
                    } catch (error) {
                        if (error !== 'cancel') {
                            Auth.clearUser();
                            window.location.href = 'login.html';
                        }
                    }
                }
            }
        });

    </script>
</body>

</html>